﻿#region Copyright

// All Material Copyright © 2010 Dynamic Concepts Development Corp., All Rights Reserved.
//      Portions Copyright © 1984-2009 Dynamic Concepts Development Corp., All Rights Reserved.
// For further information please contact: SoftwareSupport@dynconcepts.com
// Dynamic Concepts Development Corp.  311 W 57th St. Suite #422, New York, NY 10019

#endregion

#region Using References

using System.Windows.Input;
using System.Windows.Threading;

#endregion

namespace DynConDevCorp.OpenArch.DynAppFramework.Tiers.UserInterface.WPF.Engine
{
    public abstract class CommandHandlerBase : ICommandHandler
    {
        #region Constructors

        protected CommandHandlerBase(RoutedUICommand command)
        {
            r_CreationDispatcher = Dispatcher.CurrentDispatcher;
            r_Command = command;
            InitializeCanExecuteParameters();
            CommandHandlersManager.Register(this);
        }

        #endregion

        #region Public Properies and Indexers

        public RoutedUICommand Command
        {
            get { return r_Command; }
        }

        #endregion

        #region Public Methods

        public void CommandCanExecute(object sender, CanExecuteRoutedEventArgs args)
        {
            UpdateCanExecuteStatus();
            args.CanExecute = CanExecute;
            args.ContinueRouting = ContinueRouting;
            args.Handled = Handled;
        }

        public void CommandExecuted(object sender, ExecutedRoutedEventArgs args)
        {
            UICommandManager.GlobalInstance.CommandExecuted(sender, r_Command);
            InitiateCommand(sender, args);
        }

        #endregion

        #region Protected Properties and Indexers

        protected bool CanExecute { get; set; }
        protected bool ContinueRouting { get; set; }

        protected Dispatcher CreationDispatcher
        {
            get { return r_CreationDispatcher; }
        }

        protected bool Handled { get; set; }

        #endregion

        #region Protected Methods

        protected abstract void InitiateCommand(object sender, ExecutedRoutedEventArgs args);

        protected bool InvokeRequired()
        {
            return !r_CreationDispatcher.CheckAccess();
        }

        protected virtual void UpdateCanExecuteStatus()
        {
        }

        #endregion

        #region Private Methods

        private void InitializeCanExecuteParameters()
        {
            CanExecute = true;
            ContinueRouting = false;
            Handled = true;
        }

        #endregion

        #region Instance Fields (ReadOnly)

        private readonly RoutedUICommand r_Command;

        #endregion

        #region Instance Fields (ReadOnly)

        private readonly Dispatcher r_CreationDispatcher;

        #endregion
    }
}